﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chaos.messages
{
    class request_lock_faction : message
    {
        String m_faction;   
        public String Faction
        {
            get { return m_faction; }
            set { m_faction = value; }
        }

        bool m_lock;
        public bool Lock
        {
            get { return m_lock; }
            set { m_lock = value; }
        }

        public override void process(context in_context)
        {
            model.appinfo appinfo = System.Windows.Application.Current.FindResource("model_appinfo") as model.appinfo;
            if (appinfo != null)
            {
                if (appinfo.HostName == in_context.Connection.User)
                {
                    LockFactionEvent e = new LockFactionEvent();
                    e.Faction = Faction;
                    e.Lock = Lock;
                    System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                        new OnLockFactionDelegate(OnLockFactionUIThread), e);          
                }
            }
        }

        public override void serialize(stream.stream in_Stream)
        {
            in_Stream.begin("request_lock_faction")   
                .serialize("faction", ref m_faction)
                .serialize("lock", ref m_lock)
            .end();
        }

        public class LockFactionEvent : EventArgs
        {
            public String Faction { get; set; }
            public bool Lock { get; set; }

            public LockFactionEvent()
            {
            }
        };
        public delegate void OnLockFactionDelegate(LockFactionEvent e);

        public void OnLockFactionUIThread(LockFactionEvent e)
        {
            model.game g = System.Windows.Application.Current.FindResource("model_game") as model.game;
            if (g != null)
            {
                model.faction f = g.findfactionbyname(Faction);
                if (f != null)
                {
                    f.Locked = Lock;
                }

                network.gameserver s = System.Windows.Application.Current.FindResource("game_server") as network.gameserver;
                if (s != null)
                {
                    process_model_game message = new process_model_game();
                    message.Game = g;
                    s.BroadcastMessage(message);
                }
            }
        }
    }
}
